from django.shortcuts import render

from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from  django.urls import reverse
from django.contrib.auth.hashers import make_password, check_password
from back.models import *
import random,os,time
from django.db.models import Q
# Create your views here.



#首页
def index(request):

    return render(request, 'home/index.html')
#商品列表
def list(request):

    return render(request,'home/list.html')

#商品详情
def content(request):

    return render(request,'home/content.html')

#搜索页面
def search(request):

    return render(request,'home/index.html')
#会员登录
def login(request):
    if request.method == 'GET':
        return render(request,'home/login.html')
    elif request.method == 'POST':
        pass

#会员退出
def loginout(request):

    del request.session['vipuser']

    return HttpResponseRedirect(reverse('login'))


#会员注册
def register(request):
    if request.method == 'GET':

        return render(request,'home/register.html')
    elif request.method == 'POST':
        try:
            object = User()
            object.username = request.POST.get('username')
            object.u_phone = request.POST.get('phone')
            object.password = make_password(request.POST.get('password'), None, 'pbkdf2_sha256')
            object.save()
            request.session['vipuser']={'username':object.username,'level':object.u_level.l_name,'id':object.id}
            return render(request,'home/msg.html',{'msg':'恭喜你注册成功!现在开启购物之旅,祝您购物愉快！'})

        except:
            return render(request,'home/index.html')
        #return HttpResponse(0)


#会员注册检测用户名
def checkusername(request):
    val = request.GET.get('username')
    print(val)
    try:
        res= User.objects.filter(username__contains=val)
        if res[0]:
            return JsonResponse({"rel": 1})
        else:
            return JsonResponse({"rel": 0})
    except:
        return JsonResponse({'code':-1})
    #return HttpResponse(00)



#会员登录校验用户名密码
def login_check(request):
    uname = request.GET.get('username')
    pwd = request.GET.get('password')
    try:
        res = User.objects.get(username=uname)
        if res:
            depwd = check_password(pwd,res.password)
            if depwd:
                request.session['vipuser']={'id':res.id,'username':res.username}
                #return HttpResponseRedirect(reverse('index'))
                return JsonResponse({'code':1,'href':reverse('index')})
        return JsonResponse({'code':0})
    except:

        return  JsonResponse({ 'code':-1 })
    #return HttpResponse(11)


#重置密码
def resetpwd(request):

    return render(request,'home/index.html')


def forgotpwd(request):

    return render(request,'home/forgot-pwd.html')



#====================================会员中心===================
#会员中心
def member(request):

    data = User.objects.get(id = request.session['vipuser']['id'])

    return render(request,'home/uc.html',{'data':data})

#个人头像
def uc_buddha(request):
    #获取前台传输的文件
    getfile = request.FILES.get('file')
    id = request.POST.get('id')

    #得到当前对象
    object = User.objects.get(id=id)

    try :
        picpath = upload(request)
        #判断是否是默认头像
        if getfile == '/static/default/time.jpg':
            object.u_pic = '/static/default/time.jpg'
        else:

            object.u_pic = picpath
        #保存修改
        object.save()
        return JsonResponse({"code": 0, "msg": "上传成功", "data": {"src": picpath}})
    except:
        return JsonResponse({"code": 1, "msg": "上传失败", "data": {"src": picpath}})



#个人信息
def uc_account(request):

    if request.method == 'GET':         #个人信息页面
        data = User.objects.get(id=request.session['vipuser']['id'])
        return render(request,'home/uc-account.html',{'data':data})
    elif request.method == 'POST':      #修改会员信息
        try:
            id = request.POST.get('uid')
            object = User.objects.get(id=id)

            if request.POST.get('province'):
                addpath = request.POST.get('province','') + ',' + request.POST.get('city','') + ',' + request.POST.get('area','')
            else:
                addpath=''
            object.truename = request.POST.get('truename')
            object.sex = request.POST.get('sex')
            object.age = request.POST.get('age')
            object.u_phone = request.POST.get('phone')
            object.u_address = addpath
            object.u_intro = request.POST.get('intro')
            object.save()

            return JsonResponse({'code':1})
        except:

            return JsonResponse({'code':0})
        # return HttpResponse(0)


#收货地址
def uc_address(request):

    return render(request,'home/uc-address.html')

#我的订单
def uc_myorder(request):

    return render(request,'home/uc-order.html')

#订单详情
def uc_order_detail(request):

    return render(request,'home/uc-order-detail.html')

#商品评价
def uc_evaluate(request):

    return render(request,'home/uc-evaluate.html')





#===================================================================================

#信息提示
def msg(request):

    return render(request,'home/msg.html',{'msg':'默认提示'})


#上传会员头像
def upload(request):
    #获取前台传输的文件
    getfile = request.FILES.get('file')
    id = request.POST.get('id')
    #得到源文件的后缀
    hz = getfile.name.split('.').pop()
    #生成新的名称
    make_name = time.strftime("%Y%m%d", time.localtime())+'_'+id+'.'+hz
    #生成文件夹
    make_dir = './media/images/user/'+time.strftime("%Y%m%d", time.localtime())+'/'
    print(make_dir)
    if os.path.exists(make_dir):
        make_dir = make_dir
    else:
        os.makedirs(make_dir)
    print(11)
    #写入文件
    try:
        with open(make_dir+make_name, 'wb+') as pic:
            for p in getfile.chunks():
                pic.write(p)
    except:
        return False
    u_pic = make_dir+make_name
    return u_pic[1:]







